<template>
  <div class="app-container bg-white">
    <el-form :inline="true" size="small" ref="form" :model="myForm">
      <el-form-item>
        <el-input size="small" v-model.trim="myForm.name" placeholder="请输入设备名称" clearable maxlength="30"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input size="small" v-model.trim="myForm.code" placeholder="请输入设备编号" clearable maxlength="30"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input size="small" v-model.trim="myForm.mchName" placeholder="请输入商户名称" clearable maxlength="30"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input size="small" v-model.trim="myForm.storeName" placeholder="请输入门店名称" clearable maxlength="30"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select size="small" v-model="myForm.status" placeholder="请选择在线状态" clearable>
          <el-option v-for="item in statusDataList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="small" v-model="myForm.enableStatus" placeholder="请选择启用状态" clearable>
          <el-option v-for="item in enableStatusDataList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" class="width_104" @click="getPageDataList()">查询</el-button>
        <el-button size="small" class="width_104" @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-button size="mini" type="success" icon="el-icon-document-add" @click="addOption()">新增设备</el-button>
    </div>
    <el-table class="margin_top_20" ref="multipleTableContent" :data="pageData" stripe :header-cell-style="tableHeaderStyle" v-loading="loading">
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column prop="equipmentName" label="设备名称"></el-table-column>
      <el-table-column prop="equipmentNo" label="设备编号"></el-table-column>
      <el-table-column prop="userCount" label="绑定人数"></el-table-column>
      <el-table-column prop="status" label="设备在线状态">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.status == 0">在线</el-tag>
          <el-tag size="small" v-else>离线</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mchName" label="商户名称"> </el-table-column>
      <el-table-column prop="mchId" label="商户编码"> </el-table-column>
      <el-table-column prop="storeName" label="门店名称"> </el-table-column>
      <el-table-column prop="storeId" label="门店编码"></el-table-column>
      <el-table-column prop="enableStatus" label="是否启用">
        <template slot-scope="scope">
          <el-switch class="lef" :value="scope.row.enableStatus == 0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="activationTime" label="激活时间"></el-table-column>
      <el-table-column label="操作" width="240">
        <template slot-scope="scope">
          <button class="my-btn my-btn--mini my-btn--primary plain" @click="editOption(scope.row)">编辑</button>
          <button class="my-btn my-btn--mini my-btn--danger plain" @click="delOption(scope.row.id)">删除</button>
          <!-- <button class="my-btn my-btn--mini my-btn--primary plain" @click="BindingDevice(scope.row)">修改门店</button>
            <button class="my-btn my-btn--mini my-btn--danger plain" @click="addUnfasten(scope.row)">加绑</button>
            <button class="my-btn my-btn--mini my-btn--danger plain" @click="unBindOption(scope.row)">解绑</button> -->
          <el-dropdown class="margin_left_10" trigger="click" @command="menuClick($event, scope.row)">
            <button class="my-btn my-btn--mini my-btn--primary plain">更多菜单</button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">修改门店</el-dropdown-item>
              <el-dropdown-item command="b">加绑</el-dropdown-item>
              <el-dropdown-item command="c">解绑</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="text-center">
      <br />
      <el-pagination background @size-change="handleSizeChange" @current-change="handlePagingChange" :current-page="pageIndex" :page-sizes="pageSizes" :page-size="pageSize" :layout="paginationLayout" :total="pageCount"> </el-pagination>
    </div>

    <!-- 修改门店的弹窗 -->
    <!-- <el-dialog title="修改门店" :visible.sync="isEditBindDialog" width="720px">
      <el-form :inline="true" size="small" ref="form" :model="storeParameter">
        <el-form-item>
          <el-input size="small" v-model.trim="storeParameter.mchName" placeholder="请输入商户名称" clearable maxlength="30"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input size="small" v-model.trim="storeParameter.storeName" placeholder="请输入门店名称" clearable maxlength="30"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" class="width_104" @click="shopMethod()">查询</el-button>
          <el-button size="small" class="width_104">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table class="alldata" :data="ShopsData" stripe style="width: 100%; overflow: auto" :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
        <el-table-column width="50">
          <template scope="scope"> <el-checkbox v-model="checked" @change="checkedChange(scope.row)"></el-checkbox></template>
        </el-table-column>
        <el-table-column prop="mchId" label="商户编码"></el-table-column>
        <el-table-column prop="mchName" label="商户名称"></el-table-column>
        <el-table-column prop="id" label="门店ID"></el-table-column>
        <el-table-column prop="storeName" label="门店名称"></el-table-column>
        <el-table-column prop="storeImg" label="门店图片">
          <template slot-scope="scope">
            <img :src="'https://yswl-cloud-service.obs.cn-north-4.myhuaweicloud.com/' + scope.row.storeImg" alt="" width="80" height="80" />
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
      </el-table>
      <el-pagination class="fy" :page-sizes="[10, 50, 100, 200]" background :page-size="storeParameter.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalNum" @current-change="storePaging" @size-change="storeSizeChange" :current-page="storeParameter.pageNum"> </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditBindDialog = false">取 消</el-button>
        <el-button type="primary" @click="Confirm">确 定</el-button>
      </div>
    </el-dialog> -->

    <!-- 加绑 -->
    <el-dialog title="绑定门店" :visible.sync="addUnbundleFormVisible" width="480px">
      <el-form :model="setShop" label-width="120px">
        <el-form-item label="所属商户" v-if="$store.state.user.userRole != 0">
          <el-input v-model="JSON.parse(this.$store.getters.userInfo).name"></el-input>
        </el-form-item>
        <el-form-item label="所属商户" v-else>
          <el-select v-model="setform.mchId" placeholder="请选择" clearable class="full-width" value-key="id" @change="selectMerchantId">
            <el-option v-for="item in merchant" :key="item.id" :label="item.mchName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属门店">
          <el-select v-model="setform.storeId" placeholder="请选择门店编码" class="full-width" v-if="$store.state.user.userRole != 0" clearable>
            <el-option v-for="item in ShopsData" :key="item.id" :label="item.storeName" :value="item.id"> </el-option>
          </el-select>
          <el-select v-model="setform.storeId" placeholder="请选择门店编码" class="full-width" v-else :disabled="!setform.mchId" clearable @blur="storeNamechantId">
            <el-option v-for="item in ShopsData" :key="item.id" :label="item.storeName" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="门店编码"  prop="ShopsValue">
            <el-input v-model="setShop.id" autocomplete="off"  placeholder="请选择门店名称"  style="width:80% !important;"></el-input>
          </el-form-item> -->
        <el-form-item label="是否启用">
          <el-switch v-model="switchValue"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUnbundleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUnfastenConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增/编辑模态框 -->
    <device-form :visible.sync="isShowFormDialog" :data="editDevice" @update="getPageDataList()"></device-form>
    <!-- 门店列表 -->
    <merchant-list :visible.sync="isEditBindDialog"></merchant-list>
  </div>
</template>

<script>
import Setting from '@/settings'
import { getMerchantList, shopMerchabt, equipmentMerchabt, compileShopMerchabt, UnlinkShopMerchabt } from '@/api/merchants'
import { GetMerchantDeviceList, DeleteMerchantDevice } from '@/views/merchant-management/services'
import DeviceForm from '@/views/merchant-management/components/deviceForm'
import MerchantList from '@/views/merchant-management/components/merchantModalList'

export default {
  components: {
    DeviceForm,
    MerchantList
  },
  data() {
    return {
      myForm: {
        name: null, //设备名称
        code: null, //设备编号
        mchName: null, //商户名
        storeName: null, //店铺名
        status: null, //在线状态
        enableStatus: null, //启用状态：0启用，1禁用
      },
      pageIndex: 1,
      pageSize: Setting.defaultTablePaginationSize,
      pageSizes: Setting.tablePaginationSizes,
      tableHeaderStyle: Setting.tableHeaderStyle,
      paginationLayout: Setting.tablePaginationLayout,
      loading: false,
      pageData: [],
      pageCount: 0,

      editDevice: '',
      isShowFormDialog: false,
      isEditBindDialog: false,

      unfasenDevice: {
        //解绑参数
        id: null, //设备id
        storeId: null, //店铺id   商户解绑店铺设备必填
        mchId: null, //商户id  平台解绑商户设备必填
      },
      switchValue: true,
      setShop: {
        //更改门店参数
        id: '', //店铺ID
        status: null, //绑定状态 0 已绑定 1未绑定
      },
      checked: false,
      totalNum: '', //门店列表分页总条数
      storeParameter: {
        //门店列表参数
        mchName: null, //商户名
        storeName: null, //店铺名
        pageNum: 1,
        pageSize: 10,
        mchId: JSON.parse(this.$store.getters.userInfo).mchId, //商户id
      },
      setform: {
        //加绑参数
        mchId: this.$store.state.user.userRole == 0 ? null : JSON.parse(this.$store.getters.userInfo).mchId, // 商户id
        storeId: null,
        equipmentName: '', //设备名称
        equipmentNo: '', //设备SN编号
        enableStatus: null, //启用状态：0启用，1禁用
        mchType: this.$store.state.user.userRole,
        // creatorId:JSON.parse(this.$store.state.user.userInfo).id,//创建人id
      },
      merchant: [], //所属商户数据
      ShopsData: [], //所属门店数据

      addUnbundleFormVisible: false, //加绑弹窗开关
      statusDataList: [
        { value: '0', label: '在线' },
        { value: '1', label: '离线' },
      ],
      enableStatusDataList: [
        { value: '0', label: '否' },
        { value: '1', label: '是' },
      ],
    }
  },
  created() {
    this.getPageDataList()
    this.merchantsList()
    if (this.$store.state.user.userRole != 0) {
      this.shopMethod(this.storeParameter)
    }
  },
  methods: {
    BindingDevice(id) {
      //修改门店打开弹窗
      this.shopMethod(this.storeParameter)
      this.isEditBindDialog = true
    },
    async Confirm() {
      //修改门店
      let res = await compileShopMerchabt(this.setShop)
      if (res.code == 200) {
        this.isEditBindDialog = false
        if (this.setShop.id) {
          this.addUnbundleFormVisible = false
        }
      }
    },
    unBindOption(item) {
      this.$confirm('您是否确定进行解绑，解绑后门店用户将更换从属关系！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            UnlinkShopMerchabt({
              id: item.id,
              mchId: this.$store.state.user.userRole == 0 ? JSON.parse(this.$store.getters.userInfo).mchId : '',
              storeId: this.$store.state.user.userRole == 0 ? '' : item.storeId,
            })
              .finally(() => (instance.confirmButtonLoading = false))
              .then(data => {
                if (data.code == 200) {
                  this.$message.success('解绑成功!')
                  done()
                } else {
                  this.$message.success('解绑失败!')
                }
              })
          } else {
            done()
          }
        },
      }).then(() => {
        this.getPageDataList()
      })
    },
    addUnfasten(val) {
      //加绑打开弹窗
      this.addUnbundleFormVisible = true
      this.setform.equipmentName = val.equipmentName
      this.setform.equipmentNo = val.equipmentNo
      this.setform.enableStatus = val.enableStatus
    },
    async addUnfastenConfirm() {
      //加绑
      this.setform.enableStatus = this.switchValue ? 0 : 1
      let res = await equipmentMerchabt(this.setform)
      if (res.code == 200) {
        this.$message.success('绑定成功！')
        this.addUnbundleFormVisible = false
        location.reload()
      }
    },
    handlePagingChange(event) {
      this.pageIndex = event
      this.getPageDataList()
    },
    handleSizeChange(event) {
      this.pageIndex = 1
      this.pageSize = event
      this.getPageDataList()
    },
    getPageDataList() {
      this.loading = true
      GetMerchantDeviceList({
        // storeId: , // 店铺id
        mchId: JSON.parse(this.$store.getters.userInfo).mchId, // 商户id
        equipmentName: this.myForm.name, // 设备名称
        equipmentNo: this.myForm.code, // 设备编号
        mchName: this.myForm.mchName, // 商户名
        storeName: this.myForm.storeName, // 店铺名
        status: this.myForm.status, // 设备状态：0在线，1隐藏
        enableStatus: this.myForm.enableStatus, // 启用状态：0启用，1禁用
        pageNum: this.pageIndex,
        pageSize: this.pageSize,
      })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data && data.code == 200) {
            this.pageData = data.data.list
            this.pageCount = data.data.total

            if ((!data.data.list || !data.data.list.length) && this.pageIndex > 1) {
              this.pageIndex = 1
              this.getPageDataList()
            }
          }
        })
    },
    reset() {
      this.pageIndex = 1
      this.myForm.name = ''
      this.myForm.code = ''
      this.myForm.mchName = ''
      this.myForm.storeName = ''
      this.myForm.status = ''
      this.myForm.enableStatus = ''
      this.getPageDataList()
    },
    addOption() {
      this.editDevice = null
      this.isShowFormDialog = true
    },
    editOption(rowData) {
      this.editDevice = rowData
      this.isShowFormDialog = true
    },
    delOption(rowId) {
      this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            DeleteMerchantDevice({ id: rowId })
              .finally(() => (instance.confirmButtonLoading = false))
              .then(data => {
                if (data.code == 200) {
                  this.$message.success('删除成功!')
                  done()
                } else {
                  this.$message.success('删除失败!')
                }
              })
          } else {
            done()
          }
        },
      }).then(() => {
        this.getPageDataList()
      })
    },
    menuClick(event, rowData) {
      switch (event) {
        case 'a':
          this.BindingDevice(rowData)
          break
        case 'b':
          this.addUnfasten(rowData)
          break
        case 'c':
          this.unBindOption(rowData)
          break
        default:
          break
      }
    },
    async merchantsList() {
      //获取商户数据
      let merRes = await getMerchantList()
      if (merRes.code == 200) {
        this.merchant = merRes.data.list
      }
    },
    async shopMethod(option) {
      //获取门店数据
      let shopRes = await shopMerchabt(option)
      if (shopRes.code == 200) {
        this.ShopsData = shopRes.data.list
        this.storeParameter.pageSize = shopRes.data.pageSize
        this.totalNum = shopRes.data.total
      }
    },
    selectMerchantId(val) {
      //所属商户ID选择触发
      let getShop = {}
      getShop.pageNum = 1
      getShop.pageSize = 100
      ;(getShop.mchId = this.$store.state.user.userRole == 0 ? val : JSON.parse(this.$store.getters.userInfo).mchId), //商户id
        this.shopMethod(getShop)
    },
    storeNamechantId(val) {
      //所属门店ID选择触发
      if (!this.ShopsData.length) {
        this.$message.error('该商户下没有店铺,请新建店铺！')
      }
    },
    paging(val) {
      //分页操作
      this.myForm.pageNum = val
      this.getPageDataList()
    },
    handleSizeChange(val) {
      this.myForm.pageSize = val
      this.myForm.getPageDataList()
    },
    storePaging(val) {
      //门店列表分页操作
      this.storeParameter.pageNum = val
      this.shopMethod()
    },
    storeSizeChange(val) {
      this.storeParameter.pageSize = val
      this.shopMethod()
    },
    checkedChange(item) {
      //多选框触发
      // this.setShop.id = item.id
      // this.setShop.status = item.bindStatus
      this.setShop.id = item.id
      this.setShop.status = 0
    },

    queryDetail(row) {
      //查看详情
      this.$router.push({
        name: 'MerchantQueryshop',
        params: { id: row.id },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.width_104 {
  width: 104px;
}
</style>
